/*
 * @Author: Wanko
 * @Date: 2023-09-15 15:42:03
 * @LastEditors: Wanko
 * @LastEditTime: 2024-03-21 17:56:27
 * @Description: 
 */
const parameter = require('koa-parameter')
const fs = require('fs')
const cors = require('koa-cors') 

module.exports = (app) => {
  app.use(parameter(app))
  // 自定义异常处理中间件
  app.use(cors())
  app.use(async (ctx, next) => {
    try {
      await next()
    } catch (err) {
      if (err.code === 'INVALID_PARAM') {
        // 修改错误格式
        ctx.status = 400
        const { errors = [] } = err
        const { message, field } = errors[0]
        ctx.body = {
          error: '参数校验失败,' + `${field} ${message}`,
          details: err.message // 错误详情
        }
      } else {
        throw err // 将其他异常传递给 Koa 默认异常处理逻辑
      }
    }
  })
  fs.readdirSync(__dirname).forEach((file) => {
    if (file === 'index.js') return
    const route = require(`./${file}`)
    app.use(route.routes())
    app.use(route.allowedMethods())
  })
}
